<?php
	include("queries.php");

	function checkResult($result){
		if(!$result){
	    		die();
		}
	}

	function getMatches($start,$end){
		
		$query = getNeighborsQuery($start);
		$result = mysql_query($query);
		checkResult($result);
			
		// User Results
		$startMatches = array();
		$startN = array();
		$endN = array();

		$query = getNeighborsQuery($end);
		$resultB = mysql_query($query);
		checkResult($resultB);

		while ($rowB = mysql_fetch_assoc($resultB)) {
			$endN[] = $rowB["Neighbors"];
		}

		while ($rowA = mysql_fetch_assoc($result)) {
		
			$startN[] = $rowA["Neighbors"];
				
			$query = getNeighborsQuery($end);
			$resultB = mysql_query($query);
			checkResult($resultB);

			while ($rowB = mysql_fetch_assoc($resultB)) {
				if ($rowA["Neighbors"] == $rowB["Neighbors"]){
					$startMatches[] = $rowA["Neighbors"]; 
				}
			}
			mysql_free_result($resultB);
		}
		
		mysql_free_result($result);

		echo "START:".json_encode($startN)."\n";
		echo "END:".json_encode($endN)."\n";

		# Always include themselves
		$endMatches = $startMatches;
		$endMatches[] = $end;
		$startMatches[] = $start;

		$matches = array(
			"start" => $startMatches,
			"end" => $endMatches
		);

		return $matches;
	}
	
	function addEdge($start,$end){
		$values = "(".$start.",".$end.")";
		$query = "INSERT INTO `Edges`(`Start`, `End`) VALUES ".$values;
		$result = mysql_query($query);
		checkResult($result);
	}

	function checkForEdge($start,$end){
		$query = "
			SELECT * FROM `Edges` 
			WHERE (Start=".$start." AND End=".$end.") 
			OR    (Start=".$end." AND End=".$start.")
		";
		$result = mysql_query($query);
		checkResult($result);
		if (mysql_num_rows($result) == 1){
			echo "exists!";
			die();
		}
		return;	
	}

	function deleteGroup($groupId){

		$query = "DELETE FROM GroupMembers WHERE GroupId='".$groupId."'";
		$result = mysql_query($query);
		checkResult($result);

		$query = "DELETE FROM Groups WHERE Id='".$groupId."'";
		$result = mysql_query($query);
		checkResult($result);
	}

	function createGroup($users){

		echo "CREATING:".json_encode($users);

		$query = "INSERT INTO `Groups`(`CurrentSongPlaying`) VALUES (NULL)";
		$result = mysql_query($query);
		checkResult($result);

		$groupId = mysql_insert_id();
		foreach( $users as $user){
			$values = "('".$user."','".$groupId."')";
			$query = "INSERT INTO `GroupMembers`(`UserId`,`GroupId`) VALUES ".$values;
			$result = mysql_query($query);
			checkResult($result);
		}
	}
	
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
		mysql_connect("localhost","akosciak","MojaPtaszek");
		
		mysql_select_db("songbump") or die( "Unable to select database");
	
		$start = $_POST["start"];
		$end = $_POST["end"];

		checkForEdge($start,$end);
		$matches = getMatches($start,$end);

		# Add the edge between the two people who bumped
		addEdge($start,$end);
		
		# Update the groups
		$query = "SELECT * FROM `Groups`";
		$result = mysql_query($query);
		checkResult($result);
			
		$isNewGroup = TRUE;
		$isFirst = TRUE;
		$delGroups = array();
		$addGroups = array();
	
		# Determine if the new group is a subset or superset
		echo "Start Matches:".json_encode($matches['start'])."\n";
		echo "End Matches:".json_encode($matches['end'])."\n";
		while ($row = mysql_fetch_assoc($result)) {

			echo "=================================================\n";

			$query = "SELECT * FROM `GroupMembers` WHERE GroupId='".$row["Id"]."'";
			$resultB = mysql_query($query);
			checkResult($result);

			$group = array();
			while ($rowB = mysql_fetch_assoc($resultB)) {
				$group[] = $rowB["UserId"];
			}

			# Is it a subset
			echo "Group:".json_encode($group)."\n";
			echo "Start Intersect:".json_encode(array_intersect($group,$matches['start']))."\n";
			echo "End Intersect:".json_encode(array_intersect($group,$matches['end']))."\n";

			# Check start matches
			$intersectSize = count(array_intersect($group,$matches['start']));
			if($intersectSize == count($group)){

				echo "<-- Its a SUPERSET -->\n";
				$isFirst = FALSE;

				$delGroups[] = $row["Id"];				

				$addition = $group;
				$addition[] = $end;
				$addGroups[] = $addition;
			} 

			# Check end matches
			$intersectSize = count(array_intersect($group,$matches['end']));
			if($intersectSize == count($group)){

				echo "<-- Its a SUPERSET -->\n";
				$delGroups[] = $row["Id"];				
			} 

			mysql_free_result($resultB);
		}

		mysql_free_result($result);

		if ($isFirst){
			$firstGroup = array();
			$firstGroup[] = $start;
			$firstGroup[] = $end;
			createGroup($firstGroup);
		} else {
			foreach($addGroups as $group){
				createGroup($group);
			}
			foreach($delGroups as $group){
				deleteGroup($group);
			}
		}	
	}
	
?>
